CSCS1002 Tutorial 9 (Guochao Xie)¶

Main topics:

  • Format
    • PEP8
    • Linting in VSCode
    • Auto format in VSCode
    • Adding comments
  • Types
    • Typing in Python
  • Tests
    • Pytest

To get prepared, you may preview the following materials and install required packages before the tutorial.

To demo, we will use the following codes from the official materials last week: The tik-tac-toe game. You should review it yourself. You can download the material codes from Blackboard (Week 10) or code here pdf here.

We will also use the code for vending_machine_class.py (Week 9). You can download it from here.

Format¶

Format is an important concept for programming. We should write readable and understandable codes so that we and other programmers can understand it.

In Python, we adopt PEP 8 as the standard of formatting.

Try to follow it and let it be your habit! Note: different languages will have different formatting convention.

How worse is your code? Enable Pylint to check!¶

VSCode has some extensions to automatically detect your formatting mistakes for you.

  1. Open VSCode.
  2. Open Command Palette (You may use ctrl + shift + p or command + shift + p).
  3. Type linter and select Python: Select Linter.
  4. Select pycodestyle. On the bottom right of your VSCode, it may prompt to you that you need to install a package. Click install.
  5. Wait for the installation of the package.
  6. Open Command Palette and type linting.
  7. Choose Python: Enable Linting.
  8. Choose on and Enter.
  9. Open sample.py.

image.png

See the red lines?

This code is provided by TA for Week 10's practice. You can run the code with few errors, but the format is actually ugly!

Every red line indicates a format mistake that violate PEP 8. If we move our mouse on a red line, we can see the hint:

image.png

Like this one, missing whitespace around operator means we need to add white space around >. Such mistakes actually make your codes ugly (and you may be deducted for your assignment)!

To fix it, add spaces around > and save.

image.png

No red lines anymore! Good!

My suggestion is that, you should at least remove all red lines to have a good format of your codes (and maybe a good result for your assignment).

However, it is sometimes tiring to manually fix all mistakes. Can we have an automated tool to do it? Sure!

Auto Format Your Code: Formatter¶

  1. Open Command Palette and type in format.
  2. Select Format Document.
  3. On the right-bottom, it may prompt to you that you need to install another package. Click install.
  4. Repeat 1-2 again.
  5. Now, your codes should be auto formatted! Save it.
  6. Now, most problems are solved. We still need to manually fix some of them.

Comment a function, method and class.¶

We use """ ... """ to comment a function or method, the line after the definition! You can have multiple lines of comments. We also add a newline after the comment.

The good news is that if you comment, you can easily view it on VSCode. The following example shows a comment on draw_board(self).

Comments can improve your efficiency of coding!

image.png

Practice: Format one of your previous codes! (Break)¶

Time: 5 mins.

You may try another linter pylint which is more strict!

Open one of your previous codes and format it. You may open your assignment 1. Try to make it prettier.

Typing¶

Python is a Object-Oriented Programming Language where every value has a type. However, variables do not. We can easily overwrite a variable using other types of value.

  • Pros: Convenient to change value.
  • Cons: You may get loss with many lines of codes. Low programming efficiency for big project.

We can have type annotations for Python. Annotation means this is only for programming process (like comments), not the executing process. You can still run codes violating the types.

Reference: https://docs.python.org/3/library/typing.html

(Preferred) Use a linter for typing¶

I suggest using mypy as the linter for codes with typing. The similar procedure as above, select and install mypy as the linter now.

Typing Format¶

  • var = value ⇒ var: type = value
  • def function(var1, var2) ⇒ def function(var1: type1, var2: type2) -> returnType.

Let's look at the code for vending_machine_class.py. First, let's format it using auto format.

image.png

How to format this function add_money?

image.png

How to have the type for list, tuple, dict?

from typing import List, Tuple, Dict and we can use them.

image.png

If we mis-use a type, the linter will help us detect it. The mis-usage of typing will give you potential dangerous bugs!

The following shows you that you miss a return!

image.png

Practice Typing (Break)¶

Time: 5 mins

Practice Typing by modifying your previous codes.

Note: Typing is not required for assignments. But you can use it to improve your efficiency!

Tests¶

Unit tests are important when developing a big project. You may need to test functions before combining them into a big program.

First of all, let's install pytest:

  • Windows: pip install -U pytest
  • Mac / Linux: sudo pip3 install -U pytest

Reference: https://docs.pytest.org/en/latest/

Create a file named function.py:

def check_age(age: int) -> int:
    if age <= 12:
        return 0
    elif age <= 17:
        return 1
    else:
        return 2

How to test it?

Create a file name test_function.py:

from function import check_age

def test_check_age():
    assert check_age(11) == 0
    assert check_age(12) == 0
    assert check_age(13) == 1
    assert check_age(17) == 1
    assert check_age(18) == 2

Here, assert will throw error when the following statement is False. Otherwise, no error and our tests will pass.

To test it, run pytest!

image.png

For pytest, we need to create a file named like test_XXXXX.py or XXX_test.py. And we need to specify functions named with test as well.

Then, we use pytest [files] to run the test. If no files are specified, pytest will test all files named with test under the folder.

For a huge project where people collaborate together, we need unit tests to ensure everyone is writing the correct functions. Otherwise, when bugs occur, we don't know who makes the mistakes and need great effort to solve.

For the assignments, you may not need typing and testing. But in the future you will need them! Hope you can have more practices after tutorial and enjoy programming!

Next week's topic: numpy, pandas and matplotlib.